#include "func_pwm.h"
#include "tim.h"
#include "usb_com.h"

void pwm_set_param(unsigned char cmd, unsigned char subCmd, unsigned char *data)
{
    TIM_HandleTypeDef *htim;
    if (data[5] == 0)
    {
        htim = &htim4;
        __HAL_TIM_SET_PRESCALER(htim, (data[8] << 8) + data[9]);
        __HAL_TIM_SET_AUTORELOAD(htim, (data[6] << 8) + data[7]);
        __HAL_TIM_SET_COMPARE(htim, TIM_CHANNEL_1, (data[10] << 8) + data[11]);

    }
    else if (data[5] == 1)
    {
        htim = &htim2;
        __HAL_TIM_SET_PRESCALER(htim, (data[8] << 8) + data[9]);
        __HAL_TIM_SET_AUTORELOAD(htim, (data[6] << 8) + data[7]);
        __HAL_TIM_SET_COMPARE(htim, TIM_CHANNEL_1, (data[10] << 8) + data[11]);
    }
    else
    {
        goto err;
    }
    
    usb_cmd(COMM_PWM, COMM_SUB_PWM_SET_PARAM, (void *)COM_OK);
    return;
err:
    usb_cmd(COMM_PWM, COMM_SUB_PWM_SET_PARAM, (void *)COM_FAIL);
}

void pwm_open_close(unsigned char cmd, unsigned char subCmd, unsigned char *data)
{
    if (data[5] == 0)
    {
        if (data[6] == 0)
        {
            if (HAL_TIM_PWM_Stop(&htim4, TIM_CHANNEL_1) != HAL_OK)
            {
                goto err;
            }
        }
        else
        {
            HAL_TIM_Base_Start(&htim4);
            if (HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_1) != HAL_OK)
            {
                goto err;
            }
        }

    }
    else if (data[5] == 1)
    {
        if (data[6] == 0)
        {
            if (HAL_TIM_PWM_Stop(&htim2, TIM_CHANNEL_1) != HAL_OK)
            {
                goto err;
            }
        }
        else
        {
            if (HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1) != HAL_OK)
            {
                goto err;
            }
        }

    }
    else
    {
        goto err;
    }
    usb_cmd(COMM_PWM, COMM_SUB_PWM_OPEN_CLOSE, (void *)COM_OK);
    return;
err:
    usb_cmd(COMM_PWM, COMM_SUB_PWM_OPEN_CLOSE, (void *)COM_FAIL);
}